<?php
/**
 * 定时任务，每天晚上12:00执行一次，就是对于发货时间超过15天的订单做自动收货处理。
 */
require_once(dirname(__FILE__)."/../config/include.php");


$GLOBALS['DEBUG_SQL_LOG'] = false ;


sql_connect() ;

function log_save_vip($logs)
{
    $time = date("Ymd H:i:s") ;
    $save_log_filename = dirname(__FILE__)."/log_core_trade.txt" ;
    file_put_contents($save_log_filename,"$time -- $logs .\r\n",FILE_APPEND);
}

$tmend = 15 * 24 * 60 * 60 ; // 15天

log_save_vip("开始搜索发货时间超过15天的用户") ;

//while(true){
	//取得订单表中已经发货的订单
	$tradelist = sql_fetch_rows("select *,unix_timestamp(curdate()) as NOWDAY from `pay_trade` where trade_state=7 ") ;
	//存在订单每个订单进行处理
	if (is_array($tradelist)) foreach($tradelist as &$u){
		$trade_id =  $u['id'] ;
		$nowday = $u['NOWDAY'] ;
		$uid = $u['user_id'] ;
		$trade_no = $u['trade_no'] ;

		//取得物流表中发货时间最后的时间
		$max_send_time = sql_fetch_one_cell("select max(`send_time`) from `pay_logistics` where `trade_id`=$trade_id");
		
		//最后发货时间是15天前的订单进行收货处理
		if (($max_send_time + $tmend) <= $nowday) {
	        sql_query("UPDATE `pay_logistics` SET `logistics_state`='2' WHERE (`trade_id`='$trade_id')") ;
			sql_query("UPDATE `pay_trade` SET `trade_state`='3' , `over_time` = unix_timestamp() WHERE (`id`='$trade_id')") ;
			log_save_vip("用户:".$uid."的订单" .$trade_no." 发货时间超过15天了，改为已收货.") ;
		}
	}else{
		break ;
    }
	/** 原来的逻辑
    $tradelist = sql_fetch_rows("select * , unix_timestamp(curdate()) as NOWDAY from `pay_logistics`  where unix_timestamp(from_unixtime(`send_time`,'%Y-%m-%d')) + $tmend <= unix_timestamp(curdate()) and `logistics_state` = 1 limit 50") ;
    if (is_array($tradelist)) foreach($tradelist as &$u){
        $uid = $u['user_id'] ;
        $id = $u['id'] ;
        $trade_id = $u['trade_id'] ;
        sql_query("UPDATE `pay_logistics` SET `logistics_state`='2' WHERE (`tr`='$id')") ;
        sql_query("UPDATE `pay_trade` SET `trade_state`='3' , `over_time` = unix_timestamp() WHERE (`id`='$trade_id')") ;
        log_save_vip("用户:".$uid." 发货时间超过15天了，改为已收货.") ;
    }else{
        break ;
    }
	
    if (count($tradelist) == 0){
        log_save_vip("处理完成.") ;
	break ;
    }
*/
        log_save_vip("处理完成.") ;
//}
